/**
 * @description 朋友圈 数据操作
 * @author malin
 */

const { Pyq, User } = require('../db/model')
const { PAGE_SIZE } = require('../conf/constants')

/**
 * 创建朋友圈
 * @param {number} userId 
 * @param {string} content 
 * @param {string} image 
 */
async function create( userId, content, image) {
    const result = await Pyq.create({
        userId,
        content,
        image
    })
    // console.log('创建朋友圈: ', result)
    return result.dataValues
}

/**
 * 查询用户第几页的朋友圈数据
 * @param {string} userName 
 * @param {number} page 
 */
async function getPyqListByUser(userName, page = 1) {
    let whereOpt = {}
    if (userName) whereOpt.userName = userName
    const result = await Pyq.findAndCountAll({
        limit: PAGE_SIZE,
        offset: PAGE_SIZE * (page - 1),
        order: [
            ['createdAt', 'desc']
        ],
        include: [
            {
                model: User,
                attributes: ['nickName', 'picture'],
                where: whereOpt
            }
        ]
    })
    // result.count 查询总数
    // result.rows  各个查询结果
    // result.rows[i].dataValues 真正的查询结果
    // result.rows[i].user 连表查询的user
    let pyqList = result.rows.map(row => row.dataValues)
    pyqList = pyqList.map(item => {
        item.user = item.user.dataValues
        return item
    })
    return {
        count: result.count,
        pageNum: Math.ceil(result.count/PAGE_SIZE),
        pyqList
    }
}

module.exports = {
    create,
    getPyqListByUser
}
